<template>
  <div class="ongoing-tasks-page">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span><i class="el-icon-truck"></i> 配送中任务 ({{ deliveringPackages.length }})</span>
        </div>
      </template>

      <el-empty v-if="loading" description="正在加载任务..."></el-empty>
      <el-empty v-else-if="deliveringPackages.length === 0" description="太棒了！所有任务都已完成"></el-empty>

      <div v-else class="task-list">
        <el-card v-for="pkg in deliveringPackages" :key="pkg.packageId" class="task-package-card" shadow="hover">
          <template #header>
            <div class="package-header">
              <span class="package-id">任务包ID: {{ pkg.packageId }}</span>
              <el-tag type="primary" effect="dark">配送中</el-tag>
            </div>
          </template>
          <div class="package-content">
            <div class="info-row">
              <i class="el-icon-location-outline"></i>
              <strong>目的地:</strong>
              <span>{{ pkg.destination }}</span>
            </div>
            <div class="info-row">
              <i class="el-icon-box"></i>
              <strong>订单数:</strong>
              <span>{{ pkg.orderCount }} 单</span>
            </div>
            <div class="info-row">
              <i class="el-icon-money"></i>
              <strong>总赏金:</strong>
              <span class="reward">¥ {{ pkg.totalReward }}</span>
            </div>
             <div class="info-row">
              <i class="el-icon-collection-tag"></i>
              <strong>订单号:</strong>
              <span>{{ pkg.orderNumbers }}</span>
            </div>
          </div>
          <div class="package-footer">
            <el-button type="primary" plain size="small" @click="viewTaskDetail(pkg)">
              查看详情 & 处理
            </el-button>
            <el-button type="success" plain size="small" @click="handleComplete(pkg)">
              已送达
            </el-button>
            <el-button type="danger" plain size="small" @click="handleCancel(pkg)">
              取消配送
            </el-button>
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getTaskPackages, cancelTaskPackage, completeTaskPackage } from '@/assets/delivery.js';
const deliveringPackages = ref([]);
const router = useRouter();
const loading = ref(false);
const total = ref(0);

const searchForm = reactive({
  packageId: '',
  deliveryArea: '',
  // ... 其他搜索项
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
});

const fetchTaskPackages = async () => {
  loading.value = true;
  const queryParams = {
    page: pagination.currentPage,
    size: pagination.pageSize,
    status: "delivering", // 关键：配送中
    ...searchForm,
  };
  try {
    const response = await getTaskPackages(queryParams);
    console.log(response.data.data);
    
    if (response.data && response.data.data) {
      deliveringPackages.value = response.data.data.records || [];
      total.value = response.data.data.total || 0;
    } else {
      deliveringPackages.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error('获取配送中任务列表失败');
  } finally {
    loading.value = false;
  }
};

onMounted(fetchTaskPackages);

// 详情跳转
const viewTaskDetail = (taskPackage) => {
  router.push(`/delivery/tasks/${taskPackage.packageId}`);
};

// 取消配送
const handleCancel = async (pkg) => {
  try {
    await ElMessageBox.confirm('确定要取消该任务包的配送吗？', '提示', { type: 'warning' });
    await cancelTaskPackage(pkg.packageId);
    ElMessage.success('已取消配送，任务包回到待配送');
    fetchTaskPackages();
  } catch (e) {
    // 用户取消或出错，无需提示
  }
};

// 完成任务包
const handleComplete = async (pkg) => {
  try {
    await ElMessageBox.confirm(
      `确定要将任务包 ${pkg.packageId} 标记为已送达吗？\n此操作将完成该任务包的所有订单。`, 
      '确认送达', 
      { 
        type: 'warning',
        confirmButtonText: '确认送达',
        cancelButtonText: '取消'
      }
    );
    
    await completeTaskPackage(pkg.packageId);
    ElMessage.success('任务包已送达，订单状态已更新为已完成');
    fetchTaskPackages(); // 刷新列表
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('操作失败，请重试');
    }
  }
};

// 其他方法（搜索、分页、切换视图等）可直接复制Pending.vue
</script>

<style scoped>
.ongoing-tasks-page {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}
.task-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}
.task-package-card {
  border-left: 5px solid #409EFF;
}
.package-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.package-id {
  font-weight: bold;
  font-size: 14px;
}
.package-content .info-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
  color: #606266;
}
.info-row i {
  margin-right: 8px;
  font-size: 16px;
  color: #409EFF;
}
.info-row .reward {
  color: #F56C6C;
  font-weight: bold;
  font-size: 16px;
}
.package-footer {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #EBEEF5;
  text-align: right;
}
</style> 